<!--奖金测算-机构测算-机构测算配置-->
<template>
 <div>
   <flexible :leftCols="leftCols" ref="flexibleRef">
     <template slot="left">
       <el-form :inline="true" class="flex">
         <el-form-item label="负责部门">
           <el-select v-model="deptId" placeholder="请选择负责部门"   @change="switchDepartment" :clearable="false">
             <el-option v-for="(item,index) in fzbmData" :key="index" :label="item.deptName"
                        :value="item.deptId"></el-option>
           </el-select>
         </el-form-item>
         <el-form-item>
           <el-button type="primary" @click="addRoot" v-if="moudelType != 'xs'">新增</el-button>
           <el-button type="primary" plain @click="syncHandle" v-if="moudelType != 'xs'">同步</el-button>
           <el-button type="primary" plain @click="downLoad">下载模板</el-button>
           <el-upload
             action='/bonus/bonusdept/importRatio'
             accept=".xlsx, .xls"
             :headers="headers"
             class="upload-demo inline-block"
             :before-upload="beforeAvatarUpload"
             :on-success="handleUploadSuccess"
             :on-error="handleUploadError"
             :show-file-list="false"
             :data="importData">
             <el-button  size="small" class="ml10"  type="primary" plain >导入</el-button>
           </el-upload>
         </el-form-item>
       </el-form>
       <div class="divide"></div>
       <el-input
         placeholder="输入机构名称进行过滤"
         v-model="searchForm.name" class="mb10" clearable>
       </el-input>
       <el-table
         v-loading="treeLoading"
         :data="treeTableFilter"
         border
         :row-class-name="rowClass"
         @select="selectRow"
         @select-all="selectAllRow"
         header-align="center"
         :header-cell-style="{ background: '#f2f2f2', color: '#000' }"
         height="calc(100vh - 320px)"
         row-key="id"
         key="first"
         default-expand-all
         :tree-props="{
              children: 'children',
              hasChildren: 'hasChildren',
            }"
         ref="tableRef"
         highlight-current-row
         @row-click="rowClick"
         @selection-change="handleSelectionChange"
       >
         <el-table-column
           type="selection"
           header-align="center"
           align="center"
           width="55">
         </el-table-column>
         <el-table-column prop="name" show-overflow-tooltip label="机构名称" align="left" min-width="140">
         </el-table-column>
         <el-table-column prop="deptName" show-overflow-tooltip label="机构全称" align="left" header-align="center" min-width="140">
         </el-table-column>
         <el-table-column prop="deptCode" show-overflow-tooltip label="机构编码" align="left" header-align="center" >
         </el-table-column>
         <el-table-column prop="eccDeptCode" show-overflow-tooltip label="ECC机构编码" align="left" header-align="center" >
         </el-table-column>
         <el-table-column prop="deptRatio" show-overflow-tooltip label="机构系数" v-if="moudelType == 'xs'" align="center" header-align="center" >
         </el-table-column>
         <el-table-column prop="bonusRatio" show-overflow-tooltip label="奖金基数"  v-if="moudelType == 'xs'" align="center" header-align="center" >
         </el-table-column>
         <el-table-column align="center" width="180px" label="操作">
           <template slot-scope="scope">
             <el-button type="text" @click.stop="addSubLevel(scope.row)" v-if="moudelType != 'xs'">新增下级</el-button>
             <el-button type="text" @click.stop="edit(scope.row)">编辑</el-button>
             <el-button type="text"  class="delete_btn" @click.stop="del(false,scope.row)" v-if="moudelType != 'xs'">删除</el-button>
           </template>
         </el-table-column>
       </el-table>
     </template>
     <template slot="right">
     </template>
   </flexible>

    <!--机构新增-->
    <org-form ref="orgFormRef" :moudelType="moudelType"  :parentDeptNameTreeData="tableData" @refresh="refreshTreeData"></org-form>
 </div>
</template>

<script>
import flexible from "@/views/bonusmanage/components/flexible";
import OrgForm from "@/views/bonusmanage/basic/org/orgForm";
import {asynOrgTree,getOrgOfDept,deptDelBatch,exportExcel} from '@/api/bonus/calculateorgconfig'
import {getJiangJinBm} from "@/api/admin/dept";
import store from "@/store";
let proVal = null
export default {
  name: "index",
  props:{
    moudelType:String,
    default:''
  },
  components:{
    OrgForm,
    flexible
  },
  watch: {

  },
  computed: {
    treeTableFilter () {
      let treeData = this.tableData
      //获取需要刷选的属性
      const propList = this.exitProps(this.searchForm)
      //初始化
      proVal = {}
      //赋属性
      propList.forEach(item => {
        proVal[item] = ''
      })
      //如果都为false 则不进行过滤，直接获取所有
      if (propList.length > 0) {
        let handleTreeData = this.handleTreeData(treeData, this.searchForm, Object.keys(this.searchForm))
        this.setExpandRow(handleTreeData)
        this.expandRow = this.expandRow.join(',').split(',')
        return handleTreeData
      }

      return this.tableData
    }
  },
  data(){
    return{
      treeLoading:false,
      leftCols:24,
      fzbmData:{} ,
      tableData:[],
      expandRow: [],
      searchForm: {
        name: '',
      },
      deptId:'',
      multipleSelection:[],
      //---------------导入导出-------------
      headers: {
        Authorization: "Bearer " + store.getters.access_token,
      },
      importData: {
        jjDeptId: undefined
      }
    }
  },
  created(){
    this.getJiangJinJg() ;
  },
  methods: {
    //获取奖金管理人机构
    getJiangJinJg() {
      this.treeLoading = true ;
      getJiangJinBm().then(res => {
        if (res.data.data != null && res.data.data.length > 0) {
          this.deptId = res.data.data[0].deptId;
          this.deptName = res.data.data[0].deptName;
          this.fzbmData = res.data.data;
          this.importData.jjDeptId = this.deptId //导入用的参数
          this.getOrgTree() ;
          // this.refresh('csh');
        } else {
          // this.$notify.closeAll();
          // this.ymLoad = true;
          this.$notify.error("没有相关负责部门")
          //this.deptName = "无相关负责部门";
        }
        this.treeLoading = false ;
      }).catch(err =>{
        this.treeLoading = false ;
      });
    },
    initData(){
      this.tableData = [] ;
      this.$refs.tableRef.doLayout() ;
    },
    handleSelectionChange(list){

    },
    switchDepartment(val){
      this.getOrgTree() ;
      this.$forceUpdate() ;
    },
    refreshTreeData(){
      this.getOrgTree() ;
    },
    rowClass(){
      return "rowNavigation" ;
    },
    rowClick(item){
    },
    getOrgTree(){
      if (!this.deptId) return ;
      this.treeLoading = true ;
      getOrgOfDept({pid:this.deptId}).then(res=>{
        if (res.data.code == 0){
          this.tableData = res.data.data
        }else{
          this.$message.error('同步失败')
        }
        this.treeLoading = false ;
      }).catch(err=>{
        this.treeLoading = false ;
      })
    },
    //同步后获取该部门负责的机构
    syncHandle(){
      this.treeLoading = true  ;
      asynOrgTree({deptId:this.deptId}).then(res=>{
        if (res.data.data){
          this.getOrgTree() ;
        }else{
          this.treeLoading = false ;
          this.$message.error('同步失败')
        }

      }).catch(rr=>{
        this.treeLoading = false ;
      })
    },
    //新增根节点
    addRoot(){
      this.$refs.orgFormRef.init('addRoot','',this.deptId)
    },
    //新增下级
    addSubLevel(rowData){
      this.$refs.orgFormRef.init('add',rowData)
    },
   //编辑
    edit(rowData){
      this.$refs.orgFormRef.init('edit',rowData)
    },
    //删除
    del(batch,item){
      let msg = '' ;
      let ids = ''
      if (batch){ //批量
        msg = '确定删除选中的数据吗?'
        if (this.multipleSelection.length == 0){
          this.$message.error('请勾选要删除的数据')
          return ;
        }
        ids = this.ids.toString() ;
      }else{ //单条
        msg = '确定删除此条数据吗?'
        ids = item.id ;
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.treeLoading = true ;
        deptDelBatch({ids:ids}).then(res=>{
          this.$message.success('操作成功')
          this.getOrgTree();
          this.treeLoading = false ;
        }).catch(()=>{
          this.treeLoading = false ;
        })
      }).catch(() => {

      });
    },
    /**
     * 根据搜索条是否有值，把需要搜索的属性给保存返回
     */
    exitProps (obj) {
      let propList = []
      for (const prop in obj) {
        if (obj[prop]) {
          propList.push(prop)
        }
      }
      return propList
    },
    /**
     * 处理筛选出来的数据
     * @param treeData
     */
    setExpandRow (treeData) {
      if (treeData.length) {
        for (let i of treeData) {
          this.expandRow.push(i.id)
          if (i.children.length) {
            this.setExpandRow(i.children)
          }
        }
      }
    },
    /**
     * 过滤筛选数据
     * @param treeData 树形数据
     * @param searchForm 查询条件
     * @param searchNames 查询条件的字段 用来与树形对象匹配
     * @returns {*[]}
     */
    handleTreeData (treeData, searchForm, searchNames) {
      if (!treeData || treeData.length === 0) {
        return []
      }
      //获取需要进行筛选的属性
      const propList = this.exitProps(this.searchForm)
      const array = []
      //把搜索条件的值进行提取赋值
      propList.forEach(prop => {
        proVal[prop] = searchForm[prop]
      })
      treeData.forEach(item => {
        let match = false
        //搜索条件的值是否和数据相匹配
        let isEqual=true
        propList.forEach(prop => {
          isEqual = isEqual && item[prop].includes(proVal[prop])
        })
        match |= isEqual
        if (this.handleTreeData(item.children, searchForm, searchNames).length > 0 || match) {
          array.push({
            ...item,
            children: this.handleTreeData(item.children, searchForm, searchNames),
          })
        }
      })
      return array
    },
    /**
     * 从静态地址汇总下载模板静态文件，复杂情况不能使用这种方式
     */
    downLoad() {
      let data = this.$refs.tableRef.selection;
      if (data.length == 0) {
        this.$message.error("请勾选要下载的数据！");
        return;
      }

      let filename = "机构测算配置" + ".xlsx";
      let ids = [];
      for (let i = 0; i < data.length; i++) {
        ids.push(data[i].bonusDeptId);
      }
      this.treeLoading = true ;
      exportExcel({
        ids: ids,
      }).then((response) => {
        this.$message.success("导出成功!");
        let url = window.URL.createObjectURL(new Blob([response.data]));
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", filename);
        document.body.appendChild(link);
        link.click();
        this.treeLoading = false ;
      }).catch(err=>{
        this.treeLoading = false ;
      });
    },

//--------------------导入导出------------
    /**
     * 文件上传前
     */
    beforeAvatarUpload(file) {
      this.loading = this.$loading({
        lock: true,
        text: '文件上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    /**
     * 文件上传成功到pigx的统计文件管理后转发
     */
    handleUploadSuccess(response, file, fileList) {
      this.loading.close()
      if (response.data) {//如果解析数据中由特殊情况，向前台返回1，有错误数据返回2
        if (response.data == 2) {
          this.$message.error(response.msg)
        } else {
          this.$message.warning(response.msg)
        }
      } else {
        this.getJiangJinJg() ;
        this.$message.success(response.msg)
      }
    },
    handleUploadError(response, file, fileList) {
      this.loading.close()
      this.$message.error('上传出错：' + response.message)
    },
    // 勾选父节点时，子层级一起勾选或一起取消勾选
    selectRow(selection, row) {
      let data = selection.some((item) => {
        return row.id === item.id;
      });
      if (data) {
        // 勾选节点时
        if (row.children) {
          this.setChildren(row.children, true);
        }
      } else {
        // 取消勾选节点时
        if (row.children) {
          this.setChildren(row.children, false);
        }
      }
    },
    // 全选按钮
    selectAllRow(selection) {
      // 全选
      let isSelect = selection.some((item) => {
        let tableDataIds = this.treeTableFilter.map((data) => data.id);
        if (tableDataIds.indexOf(item.id) !== -1) {
          return true;
        } else {
          return false;
        }
      });
      // 全不选
      let isCancel = !this.treeTableFilter.every((item) => {
        let selectIds = selection.map((data) => data.id);
        if (selectIds.indexOf(item.id) !== -1) {
          return true;
        } else {
          return false;
        }
      });
      if (isSelect) {
        selection.map((item) => {
          if (item.children) {
            this.setChildren(item.children, true);
          }
        });
      }
      if (isCancel) {
        this.treeTableFilter.map((item) => {
          if (item.children) {
            this.setChildren(item.children, false);
          }
        });
      }
    },
    // 父节点含多个子层级
    setChildren(children, type) {
      children.map((item) => {
        this.toggleSelection(item, type);
        if (item.children) {
          this.setChildren(item.children, type);
        }
      });
    },
    toggleSelection(row, select) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.tableRef.toggleRowSelection(row, select);
        });
      }
    },
  }
}
</script>

<style scoped>

</style>
